package net.acoinWork.dynRender.render;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.log.NullLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;

/**
 * 渲染器,采用velocity引擎
 *
 * @author xusk
 * @Date: 15/12/31 下午12:16
 */
public enum VelocityRenderer implements Renderer<VelocityContext> {
    INSTANCE;
    private static final String FILE_RESOURCE_LOADER_CLASS = "file.resource.loader.class";
    private static final VelocityEngine ve = new VelocityEngine();//性能,单例引擎,即使多个dao实例化多个Renderer,Engine实例也是单个

    static {
        ve.setProperty(FILE_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
        ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
        ve.init();
    }

    @Override
    public String render(String preRender, VelocityContext ctx) {
        String result = "<null>";
        StringWriter sw = new StringWriter();
        ve.evaluate(ctx, sw, this.getClass().getName(), preRender);
        result = sw.toString();
        return result;
    }

    @Override
    public void loadLib(String libContent) {
        render(libContent, null);
    }


}
